package com.example.mykotlin.base.config

import java.util.concurrent.Executors
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.task.AsyncTaskExecutor
import org.springframework.core.task.support.TaskExecutorAdapter
import org.springframework.scheduling.annotation.EnableAsync
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
import org.springframework.web.filter.CorsFilter


@Configuration
@EnableAsync
class SpringConfig {
    @Bean
    fun taskExecutor(): AsyncTaskExecutor = TaskExecutorAdapter(Executors.newVirtualThreadPerTaskExecutor())

    // @Bean
    // fun virtualThreadExecutorCustomizer(): TomcatProtocolHandlerCustomizer<*> =
    //     TomcatProtocolHandlerCustomizer<ProtocolHandler> { protocolHandler ->
    //         protocolHandler.executor = Executors.newVirtualThreadPerTaskExecutor()
    //     }


    @Bean
    fun corsFilter(): CorsFilter {
        // 1.创建 CORS 配置对象
        val config = CorsConfiguration()
        // 支持域
        config.addAllowedOriginPattern("*")
        // 是否发送 Cookie
        config.allowCredentials = true
        // 支持请求方式
        config.addAllowedMethod("*")
        // 允许的原始请求头部信息
        config.addAllowedHeader("*")
        // 暴露的头部信息
        config.addExposedHeader("*")
        // 2.添加地址映射
        val corsConfigurationSource = UrlBasedCorsConfigurationSource()
        corsConfigurationSource.registerCorsConfiguration("/**", config)
        // 3.返回 CorsFilter 对象
        return CorsFilter(corsConfigurationSource)
    }

}